package com.chenfeilin.consumer.Publish_Subscribe;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

public class Consumer_PubSubQueue1 {

    public static void main(String[] args) throws
            IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException {

        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 主机地址: 默认为 localhost
        connectionFactory.setHost("localhost");
        // 连接端口: 默认为 5672
        connectionFactory.setPort(5672);
        // 虚拟主机名称: 默认为 /
        connectionFactory.setVirtualHost("/test");
        // 连接用户名: 默认为guest
        connectionFactory.setUsername("cfl");
        // 连接密码: 默认为guest
        connectionFactory.setPassword("cfl");
        // 从工厂获得连接：
        Connection connection = connectionFactory.newConnection();

        // 用连接创建Channel
        Channel channel = connection.createChannel();

        // 声明一个队列
        channel.queueDeclare("Pub_Sub_Queue1", false, false, false, null);

        // 声明一个类型为FANOUT的交换机，交换机构造方法全部参数如上
        channel.exchangeDeclare("Pub_Sub_Exchange", BuiltinExchangeType.FANOUT, false, false, null);

        // 将队列和交换机绑定
        channel.queueBind("Pub_Sub_Queue1", "Pub_Sub_Exchange", "", null);

        // 2.使用Consumer消费者接口的默认实现类DefaultConsumer完成消息的接受和消费
        // 创建消费者；并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel){

            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //收到的消息
                System.out.println("Pub_Sub_Queue1 接收到的消息为：" + new String(body, "utf-8"));
            }
        };

        //监听消息
        channel.basicConsume("Pub_Sub_Queue1", true, consumer);

    }


}
